package models;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import system.Model;

/**
 * Class Role
 * 
 * @author Rezan Achmad
 */
public class Role extends Model {

    public static int USER = 1;
    public static int ADMIN = 2;
    public static int MANAGER = 3;
    
    public int id;
    public String nama;
    public String deskripsi;

    @Override
    public boolean add() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public ArrayList<Role> getAllBySql(String sql) {
        ArrayList<Role> roles = null;

        try {
            // Execute query
            ResultSet rs = getStatement().executeQuery(sql);

            // Check result
            if (!rs.next()) {
                return null;
            }

            // Iterate all result and add to list
            Role role;
            roles = new ArrayList<Role>();
            do {
                role = new Role();
                role.setAttributes(rs);
                roles.add(role);
            } while (rs.next());

        } catch (SQLException ex) {
            Logger.getLogger(Kategori.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

        return roles;
    }

    public ArrayList<Role> getAll() {
        String sql = "SELECT * FROM `role`";
        return getAllBySql(sql);
    }

    public Role get(int roleId) {
        String sql = "SELECT * FROM `role` WHERE `id` = '" + roleId + "'";
        return getBySql(sql);
    }

    public Role getBySql(String sql) {
        ArrayList<Role> roles = getAllBySql(sql);
        return (roles != null && roles.size() > 0) ? roles.get(0) : null;
    }

    public HashMap<String, String> getListData() {
        HashMap<String, String> listData = null;
        ArrayList<Role> roles = getAll();

        if (roles != null) {
            listData = new HashMap<String, String>();
            for (Role role : roles) {
                listData.put(Integer.toString(role.id), role.deskripsi);
            }
        }

        return listData;
    }

    public static Role getInstance() {
        return new Role();
    }

    @Override
    public void setAttributes(ResultSet rs) throws SQLException {
        id = rs.getInt("id");
        nama = rs.getString("nama");
        deskripsi = rs.getString("deskripsi");
    }

    @Override
    public boolean validate() {
        return true;
    }

    @Override
    public void initAttributesLabel() {
    }
}
